import GoEasy from "goeasy-lite";
import {getOaOpenidByOpenidApi} from "@/api/home";

export type MessageCallback = (msg: any) => void;

// 内部状态
let goeasyInstance: any = null;
let pubsub: any = null;
let connected = false;
let oaOpenidByOpenidApi = "";

/**
 * 初始化 GoEasy
 */
export async function initGoEasy(appkey: string, toUserId: string, host = "hangzhou.goeasy.io") {
    if (goeasyInstance) return;
    // const res = await getOaOpenidByOpenidApi(toUserId);
    // if (res?.code === 200 && res?.data) {
    //     oaOpenidByOpenidApi = res?.data || "";
    // }
    const options: any = {
        host,
        appkey,
        modules: ["pubsub"],
        allowNotification: true
    };

    goeasyInstance = await GoEasy.getInstance(options);
    pubsub = goeasyInstance.pubsub;

}

/**
 * 建立连接
 */
export async function connectGoEasy(userId: string, userData?: Record<string, any>) {
    if (!goeasyInstance) throw new Error("请先调用 initGoEasy() 初始化");
    if (oaOpenidByOpenidApi) {
        goeasyInstance.connect({
            id: userId,
            data: userData || {},
            // wxmpId: {
            //     appid: "wx3198ca02d88cca4f",
            //     openid: oaOpenidByOpenidApi,
            // },
            onSuccess: () => {
                console.log("GoEasy 连接成功");
                connected = true;
            },
            onFailed: (error: any) => {
                console.error(
                    `GoEasy 连接失败, code: ${error.code}, msg: ${error.content}`
                );
                connected = false;
            },
            onProgress: (attempts: number) => {
                console.log("GoEasy 正在连接...", attempts);
            },
        });
    } else {
        goeasyInstance.connect({
            id: userId,
            data: userData || {},
            onSuccess: () => {
                console.log("GoEasy 连接成功");
                connected = true;
            },
            onFailed: (error: any) => {
                console.error(
                    `GoEasy 连接失败, code: ${error.code}, msg: ${error.content}`
                );
                connected = false;
            },
            onProgress: (attempts: number) => {
                console.log("GoEasy 正在连接...", attempts);
            },
        });
    }

}

/**
 * 订阅频道
 */
export function subscribeChannel(channel: string, callback: MessageCallback) {
    if (!pubsub) throw new Error("请先调用 initGoEasy() 初始化");
    console.log(channel, "通道ID")
    pubsub.subscribe({
        channel,
        onMessage: (msg: any) => {
            console.log("收到消息:", msg);
            callback(msg);
        },
        onSuccess: () => {
            console.log(`频道 ${channel} 订阅成功`);
        },
        onFailed: (error: any) => {
            console.error(
                `频道 ${channel} 订阅失败, code: ${error.code}, msg: ${error.content}`
            );
        },
    });
}

/**
 * 取消订阅频道
 */
export function unsubscribeChannel(channel: string) {
    if (!pubsub) return;
    pubsub.unsubscribe({
        channel,
        onSuccess: () => {
            console.log(`频道 ${channel} 已取消订阅`);
        },
        onFailed: (error: any) => {
            console.error(
                `取消订阅失败, code: ${error.code}, msg: ${error.content}`
            );
        },
    });
}

/**
 * 发布消息
 */
export function publishMessage(channel: string, message: string) {
    if (!pubsub) throw new Error("请先调用 initGoEasy() 初始化");

    if(oaOpenidByOpenidApi) {
        pubsub.publish({
            channel,
            message,
            // wxmpTemplateMsg: { //公众号模板消息
            //     template_id:'6wPZfFuMIUfvXGgCAHsS3tU-tn8Q9bW_Zt8fRcpRhHk', //模板id,必须字符串
            //     data:{
            //         thing8: {
            //             value: "您的咨询，有新的回复~"
            //         },
            //         thing10: {
            //             value: "我是商户端"
            //         },
            //     }, //模板消息数据
            //     url:'',  //点击消息要跳转的网页，字符串或空
            //     miniprogram:{  //点击消息要跳转的小程序，空或者两个字段都是字符串
            //         appid:'',  //小程序id
            //         pagepath:''  //小程序页面路径，必须是已上线能访问的路径
            //     }
            // },
            qos: 0,
            onSuccess: () => {
                console.log("消息发布成功");
            },
            onFailed: (error: any) => {
                console.error(`消息发送失败, code: ${error.code}, msg: ${error.content}`);
            },
        });
    } else {
        pubsub.publish({
            channel,
            message,
            qos: 0,
            onSuccess: () => {
                console.log("消息发布成功");
            },
            onFailed: (error: any) => {
                console.error(`消息发送失败, code: ${error.code}, msg: ${error.content}`);
            },
        });
    }

}

/**
 * 断开连接
 */
export function disconnectGoEasy() {
    if (!goeasyInstance) return;
    goeasyInstance.disconnect();
    connected = false;
    console.log("GoEasy 已断开连接");
}

/**
 * 获取连接状态
 */
export function isConnected() {
    return connected;
}
